
import Component from '@ember/component';
import { action } from '@ember/object';
import { ajax } from 'discourse/lib/ajax';

export default Component.extend({
  isSyncing: false,

  @action
  async syncToGitee() {
    try {
      this.set('isSyncing', true);

      let token = window.GiteeAuth.getToken();
      if (!token) {
        if (confirm('请先授权 Gitee，是否前往授权？')) {
          window.GiteeAuth.startOAuth();
        }
        return;
      }

      const topicId = this.topic.id;
      const data = await ajax(`/t/${topicId}.json`);
      const title = data.title;
      const content = data.post_stream.posts[0].cooked;

      const owner = settings.repo_owner;
      const repo = settings.repo_name;

      const res = await fetch(`https://gitee.com/api/v5/repos/${owner}/${repo}/issues`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `token ${token}`
        },
        body: JSON.stringify({
          title: (settings.issue_template_prefix || '') + title,
          body: content
        })
      });

      if (!res.ok) {
        const err = await res.text();
        throw new Error(err);
      }

      const json = await res.json();
      alert(`同步成功！已创建 Issue: ${json.html_url}`);

    } catch (e) {
      alert(`同步失败: ${e.message}`);
      console.error(e);
    } finally {
      this.set('isSyncing', false);
    }
  }
});